package com.doit.day04

import scala.io.Source

object _03_最后一个需求 {
  def main(args: Array[String]): Unit = {
    //求每一个电影类型的平均分
  /*  val tuples: Array[(String, Int)] = Array(("Animation|Children's|Comedy", 5), ("Adventure|Children's|Fantasy", 3))
    //电影名称  和  分数
    //==>想要变成什么样子呢？
    /*
    (Animation , 5)
    (Children's, 5)
    (Comedy    , 5)
    (Adventure , 3)
    (Children's, 3)
    (Fantasy   , 3)
     */

    val array: Array[(String, Int)] = tuples.flatMap(tp => {
      val movie_type: String = tp._1
      //Animation|Children's|Comedy
      val score: Int = tp._2
      val arr: Array[String] = movie_type.split("\\|")
      arr.map(ty => (ty, score))
    })

    array.foreach(println)*/

    //1193_One Flew Over the Cuckoo's Nest (1975)_Drama|action
    val movies: List[String] = Source.fromFile("C:\\Users\\34650\\Desktop\\课程资料\\资料\\movies.txt").getLines().toList

    //1_1193_5_978300760
    val ratings: List[String] = Source.fromFile("C:\\Users\\34650\\Desktop\\课程资料\\资料\\ratings.txt").getLines().toList

    val movies_map: Map[String, (String, String)] = movies.map(line => {
      //1193_One Flew Over the Cuckoo's Nest (1975)_Drama|action
      val arr: Array[String] = line.split("_")
      //电影id   电影名称  电影类型
      (arr(0), (arr(1), arr(2)))
    }).toMap

    val ratings_map: List[(String, String, String, String)] = ratings.map(line => {
      val arr: Array[String] = line.split("_")
      //1_1193_5_978300760
      (arr(0), arr(1), arr(2), arr(3))
    })

    //要的是电影类型和电影的评分
    val type_score: List[(String, Double)] = ratings_map.flatMap(tp => {
      val movie_id: String = tp._2
      val score: Double = tp._3.toDouble
      val movie_type: String = movies_map.getOrElse(movie_id, ("", ""))._2
      val arr: Array[String] = movie_type.split("\\|")
      arr.map(ty => (ty, score))
    })

    type_score.groupBy(_._1)
      .toList//为什么要toList   原来是一个Map类型，针对Map类型去调用map方法的时候，很有可能返回值类型不是一个二元元祖 就返回的是一个可迭代的
      .map(tp=>{
        val typ: String = tp._1
        val value: List[(String, Double)] = tp._2
        (typ,(value.map(_._2).sum / value.length).formatted("%.2f").toDouble)
      }).sortBy(_._1)
      .take(10)
      .foreach(println)





  }
}
